package com.wolfking.sharding.seq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
public abstract class AbstractTableSeqService extends AbstractSeqService {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    protected long loadNextId(Integer step) {
        String tableName = getTableName();
//        log.info("load nextId {}->{}", tableName, step);
        String sql = "update table_seq set id=LAST_INSERT_ID(id + ?) where table_name = ?;";
        jdbcTemplate.update(sql, step, tableName);
        return jdbcTemplate.queryForObject("select LAST_INSERT_ID()", Long.class);
    }

    @Override
    protected int getStepSize() {
        return 100;
    }

    protected abstract String getTableName();
}
